package com.qf.json;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.Dept;
import com.qf.pojo.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Apache  软件基金会， 阿里巴巴： dubbo， 百度： echarts
 *
 * Jackson: 在很多框架中到用到了jackson
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class TestJackson {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("----------java对象转换为json串----------");
        User user = new User(1, "王五", '男', "北京昌平");
        Dept dept = new Dept(2, "销售部");
        user.setDept(dept);

        String json1 = mapper.writeValueAsString(user);
        System.out.println(json1);

        System.out.println("----------json串转换为java对象-------------");
        String json11 = "{\"id\":1,\"username\":\"王五\",\"sex\":\"男\",\"address\":\"北京昌平\",\"dept\":{\"id\":2,\"name\":\"销售部\"}}";
        User u = mapper.readValue(json11, User.class);
        System.out.println(u);

        List<String> list =new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        System.out.println("----------集合转换为json串----------");
        String json2 = mapper.writeValueAsString(list);
        System.out.println(json2);
        System.out.println("----------json串转换为集合----------");
        String json22 = "[\"one\",\"two\",\"three\",\"four\",\"five\"]";
        List<String> o = mapper.readValue(json22, new TypeReference<ArrayList<String>>() {
        });
        System.out.println(o);

        List<User> users = new ArrayList<>();
        users.add(new User(1, "赵云龙", '男', "北京北科"));
        users.add(new User(2, "孙浩", '男', "北京北科"));
        users.add(new User(3, "王佳欣", '男', "北京北科"));

        System.out.println("把list集合转换为json");
        String json3 = mapper.writeValueAsString(users);
        System.out.println(json3);

        System.out.println("把json转换为list集合");
        String json33 = "[{\"id\":1,\"username\":\"赵云龙\",\"sex\":\"男\",\"address\":\"北京北科\",\"dept\":null},{\"id\":2,\"username\":\"孙浩\",\"sex\":\"男\",\"address\":\"北京北科\",\"dept\":null},{\"id\":3,\"username\":\"王佳欣\",\"sex\":\"男\",\"address\":\"北京北科\",\"dept\":null}]";
        List<User> userList = mapper.readValue(json33, new TypeReference<ArrayList<User>>(){});
        System.out.println(userList);

    }
}
